package sf.dsl.example;

import sf.database.dialect.DBDialect;
import sf.database.jdbc.sql.SQLParameter;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

public class WithinGroup extends SimpleField {
    private static final String ORDER_BY = "order by ";
    private SimpleField simpleField;
    private final List<OrderField> orderBy = new LinkedList<>();

    public WithinGroup(SimpleField simpleField) {
        this.simpleField = simpleField;
    }

    public WithinGroup orderBy(OrderField orderBy) {
        this.orderBy.add(orderBy);
        return this;
    }

    public WithinGroup orderBy(OrderField... orderBy) {
        Collections.addAll(this.orderBy, orderBy);
        return this;
    }

    @Override
    public void toConditionSql(StringBuilder sb, List<SQLParameter> list, AtomicBoolean useDefaultTableNameAlias, boolean useTablePrefix, DBDialect dialect) {
        simpleField.toConditionSql(sb, list, useDefaultTableNameAlias, useTablePrefix, dialect);
        sb.append(" within group (");
        if (!orderBy.isEmpty()) {
            sb.append(ORDER_BY);
            boolean b = false;
            for (OrderField orderField : orderBy) {
                if (b) {
                    sb.append(",");
                }
                b = true;
                orderField.toConditionSql(sb, list, useDefaultTableNameAlias, useTablePrefix, dialect);
            }
        }
        sb.append(")");
    }
}
